﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace VerificationCode
{
    public class VCode
    {
        private string Code = string.Empty;

        Color[] CodeColors = { Color.DarkGreen, Color.Blue, Color.DarkBlue, Color.Brown ,Color.DarkRed,Color.Purple,Color.Black,Color.Red,Color.OrangeRed};
        Color[] PointColors = { Color.Orange, Color.Brown, Color.Gray, Color.Pink, Color.Yellow, Color.DarkGray, Color.DarkGreen, Color.Blue, Color.DarkBlue, Color.Brown, Color.DarkRed, Color.Purple, Color.Black };
        Color[] LineColors = {Color.Orange,Color.Aqua, Color.Gray, Color.Pink ,Color.Yellow ,Color.DarkGray};

        private char[] Characters = { '1', '2', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'D', 'E', 'F', 'H', 'J', 'K', 'L','N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U'};

        public Bitmap Create(int length)
        {
            Random rdNum = new Random();
            for (int i = 0; i < length; i++)
            {
                Code += Characters[rdNum.Next(Characters.Length)];
                //Code += 'O';
            }
            int picWidth = 25 * length;
            Bitmap bmp = new Bitmap(picWidth, 40);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);

            //绘制噪线
            for (int i = 0; i < length * 2; i++)
            {
                int x1 = rdNum.Next(picWidth);
                int y1 = rdNum.Next(40);
                int x2 = rdNum.Next(x1 - picWidth / 3, x1 + picWidth / 3);
                int y2 = rdNum.Next(y1 - 16, y1 + 16);
                Pen p = new Pen(LineColors[rdNum.Next(LineColors.Length)]);
                g.DrawLine(p, x1, y1, x2, y2);
            }
            //绘制噪点
            for (int i = 0; i < length * 20; i++)
            {
                int x = rdNum.Next(picWidth);
                int y = rdNum.Next(40);
                Color clr = PointColors[rdNum.Next(PointColors.Length)];
                bmp.SetPixel(x, y, clr);
            }

            //绘制字符串
            for (int i = 0; i < Code.Length; i++)
            {
                Font ft = new Font("Consoles", 18);
                Brush bs = new SolidBrush(CodeColors[rdNum.Next(CodeColors.Length)]);
                g.DrawString(Code[i].ToString(), ft, bs, (float)i * 25, (float)8);
            }
            return bmp;
        }
    }
}
